<?php
/**
 * Bug
 * 
 * @author Tran Minh Quang
 * @version 
 */
class Model_Bug extends Zend_Db_Table_Abstract
{
    /**
     * The default table name 
     */
    protected $_name = 'bugs';
    protected $_primary = 'id';
    
    public function createBug($name, $email, $date, $url, $description, $priority, $status){
    	//create a new row in the bugs table
    	$row = $this->createRow();
    	
    	//set the row data
    	$row->author = $name;
    	$row->email = $email;
    	$dateObject = new Zend_Date($date);
    	$row->date = $dateObject->get(Zend_Date::TIMESTAMP);
    	$row->url = $url;
    	$row->description = $description;
    	$row->priority = $priority;
    	$row->status = $status;
    	
    	//Save the new row
    	$row->save();
    	
    	//now fetch the id of the row you just created and return it
    	$id = $row->id;
    	return $id;
    }
    
    public function fetchPaginatorAdaptor($filter = array(), $sortField = null, $limit = null, $page = 1){
    	$select = $this->select();
    	
    	//add filter 
    	if(count($filter)){
    		foreach ($filter as $field => $filter){
    			$select->where($field . ' = ?', $filter);
    		}
    	}
    	
    	if($sortField != '0' && !is_null($sortField)){
    		$select->order("$sortField ASC");
    	}
    	
    	$adapter = new Zend_Paginator_Adapter_DbTableSelect($select);
    	return $adapter;
    }
    
	public function updateBug($id, $name, $email, $priority, $status, $description, $date){
    	
    	$row = $this->find($id)->current();
    	if($row){
    		$row->author = $name;
    		$row->email = $email;
    		$row->priority = $priority;
    		$row->status = $status;
    		$row->description = $description;
    		$date = new Zend_Date($date);
    		$row->date = $date->get(Zend_Date::TIMESTAMP);
    		$row->save();
    		return true;
    	}
    	else{
    		throw new Zend_Exception("Update function failed, could not find row");
    	}
    }
    
    public function deleteBug($id){
    	$row = $this->find($id)->current();
    	if($row){
    		$row->delete();
    		return true;
    	}
    	else{
    		throw new Zend_Exception("Delete function failed, could not found row");
    	}
    }
}
